

PlayerManager = {};
local this = PlayerManager;

local gameObject;
local transform;
local speed = 30;
local bulletSpeed = 35;
local maxX;
local maxY;

local firePoints = {};
local hp = 100;
local score = 0;



function PlayerManager.New()
	resMgr:LoadPrefab("prefabs", {"Player"}, this.LoadOK);
end
function PlayerManager.InitData()
	local screenMax = Camera.main:ScreenToWorldPoint(Vector3(Screen.width, Screen.height));
	local boradHalf = gameObject:GetComponent("SpriteRenderer").bounds.extents;
	maxX = screenMax.x - boradHalf.x;
	maxY = screenMax.y - boradHalf.y;
	
	Event.Brocast("HpChange", hp);
	
	Event.AddListener("EnemyDead", this.OnEnemyDead);
end
function PlayerManager.LoadOK(objs)	
	gameObject = newObject(objs[0]);
	transform = gameObject.transform;
	transform.position = Vector3(0, - 4, 0);
	
	for i = 1, 2 do
		local name = "firePoint" .. i;
		table.insert(firePoints, transform:Find(name))
	end
	local luaTrigger = gameObject:AddComponent(typeof(LuaTrigger2D));	
	luaTrigger:SetEnterFunc(this.OnTriggerEnter, nil);
	
	this.InitData();
	UpdateBeat:Add(this.Update);
end

function PlayerManager.Update()
	
	this.Move();
	this.Fire();
	
end
function PlayerManager.Move()
	
	local overUI = EventSystem.current:IsPointerOverGameObject();
	if(Input.GetMouseButton(0) and not overUI) then
		local pos = Camera.main:ScreenToWorldPoint(Input.mousePosition);
		pos.z = 0;
		pos.x = Mathf.Clamp(pos.x, - maxX, maxX);
		pos.y = Mathf.Clamp(pos.y, - maxY, maxY);
		
		local vec = pos - transform.position;
		if(Vector3.SqrMagnitude(vec) < 0.5) then
			transform.position = pos;
		else
			local dir = Vector3.Normalize(vec);
			transform:Translate(dir * speed * Time.deltaTime);
		end
	end
end
local lastFireTime = 0;
function PlayerManager.Fire()
	if(Time.time - lastFireTime > 0.1) then
		lastFireTime = Time.time;
		
		for i, point in ipairs(firePoints) do
			--local go = newObject(bulletPrefab);
			local go = poolMgr:Get("PlayerBullet");
			go.transform.position = point.position;
			go.transform.rotation = point.rotation;
			local body = go:GetComponent("Rigidbody2D");
			body.velocity = point.up * bulletSpeed;
		end
	end
	
end
function PlayerManager.OnTriggerEnter(collision)
	if(collision:CompareTag("EnemyBullet")) then
		hp = hp - 1;
		Event.Brocast("HpChange", hp);
		poolMgr:Release("EnemyBullet", collision.gameObject);
		
		log("<color=red>HP:" .. hp .. "</color>");
		if(hp <= 0) then
			
			this.OnDead();
		end	
		
		
	elseif(collision:CompareTag("Enemy")) then
		hp = hp - 1;
		Event.Brocast("HpChange", hp);
		if(hp <= 0) then
			
			this.OnDead();
		end	
	end
end
function PlayerManager.OnEnemyDead()
	score = score + 1;
	Event.Brocast("ScoreChange", score);
end
function PlayerManager.OnDead()
	Event.RemoveListener("EnemyDead", this.OnEnemyDead);
	UpdateBeat:Remove(this.Update);
	gameObject:SetActive(false);
	Time.timeScale=0;
end
function PlayerManager.GetPos()
	return transform.position;
end
